package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseBindingActivity;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.contacts.activity.ContactsActivity;
import com.mingtu.doc.activity.FileDataActivity;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.IndexNewsAdapter;
import com.mingtu.jgspatrol.adapter.MenuAdapter2;
import com.mingtu.jgspatrol.adapter.NoticeBannerAdapter;
import com.mingtu.jgspatrol.bean.IndexNewsBean;
import com.mingtu.jgspatrol.bean.IndexTopNumBean;
import com.mingtu.jgspatrol.bean.MyMessageBean;
import com.mingtu.jgspatrol.bean.NoticeBean;
import com.mingtu.jgspatrol.bean.UnitNoticeTypeBean;
import com.mingtu.jgspatrol.callback.MyStringDialogCallback;
import com.mingtu.jgspatrol.databinding.ActivityOfficeBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;

public class OfficeActivity extends BaseBindingActivity<ActivityOfficeBinding> {
    private List<String> list = new ArrayList<>();
    private NoticeBannerAdapter noticeBannerAdapter;
    private boolean isLeader = SPStaticUtils.getBoolean(SPTools.isLeader);
    private IndexNewsAdapter indexNewsAdapter;
    private int noticeTypeId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_office;
    }

    @Override
    protected void initView() {
        setModuleTitle("移动办公");

        MenuAdapter2 menuAdapter = new MenuAdapter2(context, isLeader);
        binding.gridView.setAdapter(menuAdapter);
        binding.gridView.setNumColumns(2);
        menuAdapter.setOnItemClickListener(new MenuOnItenClickListner());


        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recyclerNews.setLayoutManager(manager1);
        binding.recyclerNews.addItemDecoration(new BottomSpaceItemDecoration());
        //添加自定义分割线
//        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
//        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_dive_line));
//        recycler.addItemDecoration(divider);


        indexNewsAdapter = new IndexNewsAdapter(context);
        if (isOpenLoadAnimation) {
            indexNewsAdapter.isFirstOnly(isFirstOnly);
            indexNewsAdapter.openLoadAnimation(animationType);
        }
        indexNewsAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recyclerNews.setAdapter(indexNewsAdapter);
        indexNewsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String id = indexNewsAdapter.getData().get(position).getId() + "";
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), NewsDetailsActivity.class, bundle);
            }
        });

        initListener();
//        initIMListener();
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        addClickListener(this, binding.layoutUnitNotice, binding.layoutMsgNotice, binding.layoutMoreNews, binding.layoutEvent, binding.layoutProgress);
    }

    @Override
    protected void getData() {
        getUnitNoticeType();
        setTime();
        getTopEventNum();
        getNoticeList();
        getNewList(6);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            getNoticeList();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //处理完之后刷新数据
        String message = event.getMessgae();
        if (message.equals(MyConstant.REFRESH_FIRE_NOTICE_DATA)) {

        }

    }

    private void initListener() {
        initPullRefresh();//刷新
    }

    private void initPullRefresh() {
        binding.srlUp.setEnableLoadMore(false);
        binding.srlUp.setEnableOverScrollDrag(true);
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
//                getMessageCount();
                getUnitNoticeType();
                setTime();
                getTopEventNum();
                getNoticeList();
                getNewList(6);
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.layout_msg_notice:
                //消息通知
                bundle.putInt("type", 1);
                bundle.putInt("noticeTypeId", noticeTypeId);
                IntentUtils.getInstance().readyGoForResult(ActivityUtils.getTopActivity(), NotificationActivity.class, 200, bundle);
                break;
            case R.id.layout_unit_notice:
                //单位通知
                bundle.putInt("type", 0);
                bundle.putInt("noticeTypeId", noticeTypeId);
                IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), NotificationActivity.class, bundle);
                break;
            case R.id.layout_progress:
                IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), ResultStatisticsActivity.class);
                break;
            case R.id.layout_event:
                IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), ReportedEventLeaderActivity.class);
                break;
            case R.id.layout_more_news:
                IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), ExchangeActivity.class);
                break;
        }
    }

    //领导事件
    private class MenuOnItenClickListner implements MenuAdapter2.OnItemClickListener {

        @Override
        public void onItemClick(View view, int position) {
//            boolean recordAuth = SPStaticUtils.getBoolean(SPTools.recordAuth);
            switch (position) {
                case 0:
                    //文件资料
                    IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), FileDataActivity.class);
                    break;
                case 1:
                    //通讯录
                    IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), ContactsActivity.class);
                    break;
                case 2:
                    //巡护记录
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 0);
                    IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), RecordActivity.class, bundle);
                    break;
                case 3:
                    //上报记录
                    IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), ReportRecordActivity.class);
                    break;

            }

        }
    }

    /**
     * 获取未读消息的个数
     */
//    public void getMessageCount() {
//        OkGo.<String>post(MyConstant.POST_MESSAGE_COUNT)
//                .tag(this)
//                .upJson("")
//                .execute(new MyStringDialogCallback(getActivity()) {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        String result = response.body();
//                        if (!StringUtils.isEmpty(result)) {
//                            JSONObject jsonObject = JSON.parseObject(result);
//                            String msg = jsonObject.getString("msg");
//                            if (msg.equals(Constant.RESULT_SUCCESS)) {
//                                String data = jsonObject.getString("data");
//                                if (!StringUtils.isEmpty(data)) {
//                                    try {
////                                        tvMessageNum.setText(data + "");
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                        }
//                    }
//                });
//    }

    /**
     * 获取新闻列表
     */
    private void getUnitNotice(int id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", 5);
        hashMap.put("contentType", id);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_NEWS_LIST)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                NoticeBean messageBean = new NoticeBean();
                                messageBean = gson.fromJson(result, NoticeBean.class);
                                List<NoticeBean.PageBean.ListBean> dataBeans = messageBean.getPage().getList();

                                if (dataBeans != null) {
                                    int size = dataBeans.size();
                                    if (size > 0) {
                                        binding.layoutUnitNotice.setVisibility(View.VISIBLE);
                                        List<NoticeBean.PageBean.ListBean> myDataBeans = new ArrayList<>();
                                        if (size > 5) {
                                            myDataBeans = dataBeans.subList(0, 5);
                                        } else {
                                            myDataBeans = dataBeans;
                                        }
                                        for (int i = 0; i < myDataBeans.size(); i++) {
                                            NoticeBean.PageBean.ListBean listBean = myDataBeans.get(i);
                                            String title = listBean.getContentTitle();
                                            list.add(title + "");
                                        }
                                        //自定义的图片适配器，也可以使用默认的BannerImageAdapter
                                        noticeBannerAdapter = new NoticeBannerAdapter(context, list);
                                        binding.banner.setAdapter(noticeBannerAdapter)
                                                .addBannerLifecycleObserver(OfficeActivity.this)//添加生命周期观察者
                                                .setOnBannerListener(new OnBannerListener() {
                                                    @Override
                                                    public void OnBannerClick(Object data, int position) {
                                                        Bundle bundle = new Bundle();
                                                        bundle.putInt("type", 0);
                                                        bundle.putInt("noticeTypeId", noticeTypeId);
                                                        IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), NotificationActivity.class, bundle);
                                                    }
                                                })
                                                .setIndicator(new CircleIndicator(context.getApplicationContext()), false);//设置指示器
                                    } else {
                                        binding.layoutUnitNotice.setVisibility(View.GONE);
                                    }
                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                });
    }


    /**
     * 单位通知
     */
    private void getUnitNoticeType() {
        OkGo.<String>get(MyConstant.GET_NOTICE_LIST)
                .tag(this)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UnitNoticeTypeBean unitNoticeTypeBean = new UnitNoticeTypeBean();
                                unitNoticeTypeBean = gson.fromJson(result, UnitNoticeTypeBean.class);
                                UnitNoticeTypeBean.DataBean dataBean = unitNoticeTypeBean.getData();
                                noticeTypeId = dataBean.getId();
                                getUnitNotice(noticeTypeId);

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });

    }

    private void setTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour <= 3) {
            binding.tvTime.setText("已经凌晨了，注意休息哦！");
        } else if (hour > 3 && hour <= 6) {
            binding.tvTime.setText("这个点还在工作，注意休息哦！");
        } else if (hour > 6 && hour <= 9) {
            binding.tvTime.setText("早上好！");
        } else if (hour > 9 && hour <= 11) {
            binding.tvTime.setText("上午好！");
        } else if (hour > 11 && hour <= 13) {
            binding.tvTime.setText("中午好！");
        } else if (hour > 13 && hour <= 18) {
            binding.tvTime.setText("下午好！");
        } else if (hour > 18 && hour <= 21) {
            binding.tvTime.setText("晚上好！");
        } else if (hour > 21 && hour < 24) {
            binding.tvTime.setText("夜深了，早点休息哦！");
        }
    }

    /**
     * 顶部数据数字
     */

    public void getTopEventNum() {
        OkGo.<String>post(MyConstant.POST_TASK_STA_TOTAL)
                .tag(this)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            Gson gson = GsonFactory.getSingletonGson();
                            IndexTopNumBean indexTopNumBean = new IndexTopNumBean();
                            indexTopNumBean = gson.fromJson(result, IndexTopNumBean.class);
                            IndexTopNumBean.DataBean dataBean = indexTopNumBean.getData();

                            int measureNum = dataBean.getMeasureNum();
                            int progress = dataBean.getProgress();
                            String eventNum = dataBean.getEventNum();
                            int totalMileage = dataBean.getTotalMileage();
                            String duration = dataBean.getTotalDuration();
                            String taskNum = dataBean.getTaskNum();
                            String clockNum = dataBean.getClockNum();

                            try {
                                binding.tvMeasureNum.setText(String.valueOf(measureNum));
                                binding.tvProgress.setText(String.valueOf(progress));
                                binding.tvTrackMileageNum.setText(String.valueOf(totalMileage));


                                if (!StringUtils.isEmpty(eventNum)) {
                                    binding.tvReportedNum.setText(String.valueOf(eventNum));
                                } else {
                                    binding.tvReportedNum.setText("0");
                                }

                                if (!StringUtils.isEmpty(taskNum)) {
                                    binding.tvTrackDateNum.setText(String.valueOf(taskNum));
                                } else {
                                    binding.tvTrackDateNum.setText("0");
                                }

                                if (!StringUtils.isEmpty(clockNum)) {
                                    binding.tvSignInNum.setText(String.valueOf(clockNum));
                                } else {
                                    binding.tvSignInNum.setText("0");
                                }


                                if (!StringUtils.isEmpty(duration)) {
                                    long d = 0;
                                    if (duration.indexOf(".") != -1) {
                                        String array[] = duration.split("\\.");
                                        d = Long.parseLong(array[0]);
                                    } else {
                                        d = Long.parseLong(duration);
                                    }
                                    binding.tvTrackTimeNum.setText(MyUtills.formatSeconds2(d));
                                } else {
                                    binding.tvTrackTimeNum.setText("0");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    /**
     * 显示消息角标
     */
    public void showMsgFlag() {
        binding.viewMsgFlag.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏消息角标
     */
    public void hideMsgFlag() {
        binding.viewMsgFlag.setVisibility(View.GONE);
    }

    /**
     * 获取消息列表用于判断是否显示消息角标
     */
    public void getNoticeList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", 200);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_MY_MESSAGE_LIST)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MyMessageBean messageBean = new MyMessageBean();
                                messageBean = gson.fromJson(result, MyMessageBean.class);
                                List<MyMessageBean.PageBean.RecordsBean> dataBeans = messageBean.getPage().getRecords();
                                try {
                                    List<Integer> statuList = new ArrayList<>();
                                    for (int i = 0; i < dataBeans.size(); i++) {
                                        MyMessageBean.PageBean.RecordsBean recordsBean = dataBeans.get(i);
                                        int status = recordsBean.getStatus(); //0 :未读  1：已读
                                        statuList.add(status);
                                    }
                                    List<Integer> newStatusList = new ArrayList<Integer>(new LinkedHashSet<Integer>(statuList));
                                    if (newStatusList.contains(0)) { //如果含有未读的消息
                                        showMsgFlag();
                                    } else {
                                        hideMsgFlag();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });

    }

    /**
     * 单位新闻
     *
     * @param num
     */
    private void getNewList(int num) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("num", num);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INDEX_NEWS_LIST + "/" + num)
                .tag(this)
                .upJson(str)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                IndexNewsBean indexNewsBean = new IndexNewsBean();
                                indexNewsBean = gson.fromJson(result, IndexNewsBean.class);
                                List<IndexNewsBean.DataBean> dataBeans = indexNewsBean.getData();
                                try {
                                    if (dataBeans != null) {
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        indexNewsAdapter.replaceData(dataBeans);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();

                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });
    }

    //腾讯IM 用来监听收到的消息（更新任务及通知相关逻辑）
//    private void initIMListener() {
//        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
//            @Override
//            public void onRecvNewMessage(V2TIMMessage msg) {
//                if (msg != null) {
//                    try {
//                        getTopEventNum();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//            @Override
//            public void onRecvMessageReadReceipts(List<V2TIMMessageReceipt> receiptList) {
//
//            }
//
//            @Override
//            public void onRecvMessageRevoked(String msgId) {
//
//            }
//
//            @Override
//            public void onRecvMessageModified(V2TIMMessage msg) {
//
//            }
//        });
//    }

}